package me.xiaosiqi.syt.hosp.service.impl;

import me.xiaosiqi.syt.hosp.repository.HospitalRepository;
import me.xiaosiqi.syt.hosp.repository.ScheduleRepository;
import me.xiaosiqi.syt.hosp.service.HospitalService;
import me.xiaosiqi.syt.hosp.service.ScheduleService;
import me.xiaosiqi.syt.model.hosp.Department;
import me.xiaosiqi.syt.model.hosp.Hospital;
import me.xiaosiqi.syt.model.hosp.Schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: xiaosiqi
 * @date:2022/7/31 15:00
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;


    @Override
    public void saveSchedule(Schedule schedule) {
        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (null != scheduleExist) {
            schedule.setId(scheduleExist.getId());
            schedule.setStatus(scheduleExist.getStatus());
            schedule.setCreateTime(scheduleExist.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        } else {
            schedule.setStatus(0);
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }

    }

    @Override
    public Page<Schedule> scheduleList(String hoscode, String hosScheduleId, Integer page, Integer limit) {
        Pageable pageable = PageRequest.of(page - 1, limit);
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        schedule.setHosScheduleId(hosScheduleId);
        Example<Schedule> example = Example.of(schedule, matcher);
        return scheduleRepository.findAll(example, pageable);
    }

    @Override
    public void scheduleRemove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (null != schedule){
            scheduleRepository.deleteById(schedule.getId());
        }
    }

}
